<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:overtimeapply:add']"
          class="modern-button"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:overtimeapply:edit']"
          class="modern-button"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:overtimeapply:remove']"
          class="modern-button"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:overtimeapply:export']"
          class="modern-button"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 本月加班统计卡片 -->
    <el-card
      class="box-card mb-8 modern-card"
      shadow="hover"
      @click.native="showOvertimeTips"
      :style="{ backgroundColor: getCardBackgroundColor() }"
    >
      <div slot="header" class="clearfix">
        <span>本月加班统计</span>
        <el-tooltip class="item" effect="dark" content="点击查看加班提醒" placement="top">
          <i class="fa fa-info-circle" style="float: right; padding: 3px 0; color: #409EFF;"></i>
        </el-tooltip>
      </div>
      <div class="text item">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="statistic-card">
              <i class="fa fa-clock-o statistic-icon"></i>
              <div class="statistic-title">累计加班天数</div>
              <div class="statistic-value">{{ monthStats.days || 0 }} 天</div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="statistic-card">
              <i class="fa fa-hourglass-half statistic-icon"></i>
              <div class="statistic-title">累计加班时长</div>
              <div class="statistic-value">{{ monthStats.hours || 0 }} 小时</div>
            </div>
          </el-col>
        </el-row>
        <el-progress
          :percentage="overtimePercentage"
          :color="customColors"
          :format="formatProgress"
          class="mt-10 animated-progress"
        ></el-progress>
        <div class="overtime-tips" v-if="showTips">
          <i class="fa fa-exclamation-triangle"></i>
          <span>本月已加班 {{ monthStats.hours || 0 }} 小时，请注意劳逸结合！</span>
          <div v-if="monthStats.hours > 40" class="health-tips">
            😣 长时间加班可能会导致疲劳、压力和健康问题。建议适当休息，放松身心。
          </div>
        </div>
      </div>
    </el-card>

    <el-table v-loading="loading" :data="overtimeapplyList" @selection-change="handleSelectionChange" class="modern-table">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="加班开始时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="加班结束时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="加班时长" align="center" prop="overtimeHours" />
      <el-table-column label="审批人" align="center" prop="approveName" />
      <el-table-column label="审批状态" align="center">
        <template #default="{ row }">
          <el-button
            class="uniform-btn modern-status-btn"
            :class="{
              'pending-btn': row.status === 'PENDING',
              'approve-btn': row.status === 'APPROVED',
              'reject-btn': row.status === 'REJECTED'
            }"
            :type="{
              'PENDING': 'warning',
              'APPROVED': 'success',
              'REJECTED': 'info'
            }[row.status]"
            @click="showResult(row)"
          >
            {{
              {
                APPROVED: '已通过',
                PENDING: '审批中',
                REJECTED: '已拒绝'
              }[row.status]
            }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            :disabled="scope.row.status !== 'PENDING'"
            :title="scope.row.status !== 'PENDING' ? '非待审批状态不可修改' : ''"
            v-hasPermi="['system:overtimeapply:edit']"
            class="modern-action-btn"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:overtimeapply:remove']"
            class="modern-action-btn"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改加班对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body class="modern-dialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" disabled/>
        </el-form-item>
        <el-form-item label="审批人" prop="approveid">
          <el-select
            v-model="form.approveid"
            placeholder="请选择审批人"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="item in managerOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="加班开始时间" prop="startTime">
          <el-date-picker clearable
                          v-model="form.startTime"
                          type="datetime"
                          format="yyyy-MM-dd HH:mm:ss"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="请选择加班开始时间"
                          @change="calculateHours">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="加班结束时间" prop="endTime">
          <el-date-picker clearable
                          v-model="form.endTime"
                          type="datetime"
                          format="yyyy-MM-dd HH:mm:ss"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="请选择加班结束时间"
                          @change="calculateHours">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="加班原因" prop="reason">
          <el-input
            v-model="form.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入加班原因"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" class="modern-button">确 定</el-button>
        <el-button @click="cancel" class="modern-button">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listOvertimeapply,
  getOvertimeapply,
  delOvertimeapply,
  addOvertimeapply,
  updateOvertimeapply,
  getDeptManagers,
  getMonthOvertimeStats
} from "@/api/system/overtimeapply";

export default {
  name: "Overtimeapply",
  data() {
    return {
      managerOptions: [], // 审批人选项
      monthStats: {}, // 本月加班统计
      showTips: false, // 是否显示加班提示
      customColors: [
        { color: '#67C23A', percentage: 60 },
        { color: '#E6A23C', percentage: 80 },
        { color: '#F56C6C', percentage: 100 }
      ],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 加班表格数据
      overtimeapplyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        startTime: null,
        endTime: null,
        overtimeHours: null,
        status: null,
        createdAt: null,
        updatedAt: null,
        approveid: 1,
        result: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        approveid: [
          { required: true, message: "审批人不能为空", trigger: "change" }
        ],
        userId: [
          { required: true, message: "用户ID不能为空", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: '请选择开始时间', trigger: 'change' }
        ],
        endTime: [
          {
            validator: (rule, value, callback) => {
              if (!this.form.startTime) {
                callback(new Error("请先选择开始时间"))
              } else if (new Date(value) <= new Date(this.form.startTime)) {
                callback(new Error("结束时间必须晚于开始时间"))
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ],
        reason: [
          { required: true, message: '请输入加班原因', trigger: 'blur' },
          { max: 200, message: '长度不能超过200个字符', trigger: 'blur' }
        ]
      }
    };
  },
  computed: {
    overtimePercentage() {
      const hours = this.monthStats.hours || 0;
      // 假设每月标准工作小时为160小时，加班超过这个数就是100%
      return Math.min(Math.round((hours / 160) * 100), 100);
    }
  },
  created() {
    this.userId = this.$store.state.user.id;
    this.queryParams.userId = this.userId;
    this.getList();
    this.getMonthStats();
  },
  methods: {

    /** 查询加班列表 */
    getList() {
      this.loading = true;
      listOvertimeapply(this.queryParams).then(response => {
        this.overtimeapplyList = response.rows.map(item => {
          // 添加审批人姓名
          if (item.approveName) {
            return item;
          } else {
            return {
              ...item,
              approveName: item.approveid ? '待获取' : '未指定'
            };
          }
        });
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取本月加班统计 */
    getMonthStats() {
      const params = {
        userId: this.userId,
        month: new Date().getMonth() + 1,
        year: new Date().getFullYear()
      };
      getMonthOvertimeStats(params).then(response => {
        this.monthStats = response.data;
        // 如果加班时长超过40小时显示提示
        if (this.monthStats.hours > 40) {
          this.showTips = true;
        }
      });
    },
    // 显示加班提示
    showOvertimeTips() {
      this.showTips = !this.showTips;
      if (this.showTips) {
        this.$message({
          message: `本月已加班 ${this.monthStats.hours || 0} 小时，请注意劳逸结合！`,
          type: 'warning',
          duration: 3000
        });
      }
    },
    // 进度条格式化
    formatProgress(percentage) {
      return `${percentage}% (${this.monthStats.hours || 0}/160小时)`;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        startTime: null,
        endTime: null,
        overtimeHours: null,
        status: null,
        createdTime: new Date().toISOString().split('T')[0], // 默认今天日期（格式：YYYY-MM-DD）
        updatedTime: new Date().toISOString().split('T')[0], // 默认今天日期（格式：YYYY-MM-DD）
        approveid: null, // 初始化审批人ID为空
        result: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.userId = this.userId;

      // 调用获取部门经理接口
      getDeptManagers(this.userId).then(response => {
        if (response.data && response.data.length > 0) {
          this.managerOptions = response.data.map(item => ({
            value: item.userId,
            label: item.userName  // 确保字段名正确
          }));
          // 如果有默认审批人，设置默认显示值
          if (this.managerOptions.length > 0) {
            this.form.approveid = this.managerOptions[0].value;
          }
        } else {
          this.$modal.msgWarning("当前部门没有可选的审批经理！");
        }
      }).catch(error => {
        this.$modal.msgError("获取审批人失败：" + error.message);
      });

      this.open = true;
      this.title = "添加加班";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getOvertimeapply(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改加班";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateOvertimeapply(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList(); // 直接刷新列表
            });
          } else {
            this.form.userId = this.userId;
            if (!this.form.result) {
              this.form.result = "审批还未通过，请耐心等待审批结果";
            }
            addOvertimeapply(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              this.$modal.msgError("新增失败：" + error.message);
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除加班编号为"' + ids + '"的数据项？').then(function() {
        return delOvertimeapply(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/overtimeapply/export', {
        ...this.queryParams
      }, `overtimeapply_${new Date().getTime()}.xlsx`)
    },

    showResult(row) {
      this.$alert(row.result || '暂无审批说明', '审批原因', {
        confirmButtonText: '确定'
      });
    },
    calculateHours() {
      // 当两个时间都选择时进行计算
      if (this.form.startTime && this.form.endTime) {
        const start = new Date(this.form.startTime)
        const end = new Date(this.form.endTime)

        // 验证时间有效性
        if (start >= end) {
          this.$message.warning("结束时间必须晚于开始时间")
          this.form.overtimeHours = null
          return
        }

        // 计算时间差（毫秒）
        const diff = end.getTime() - start.getTime()

        // 转换为小时（保留1位小数）
        const hours = (diff / (1000 * 60 * 60)).toFixed(1)

        // 更新加班时长
        this.form.overtimeHours = hours
      } else {
        this.form.overtimeHours = null
      }
    },
    validateEndTime(rule, value, callback) {
      if (this.form.startTime && value) {
        const start = new Date(this.form.startTime)
        const end = new Date(value)
        if (end <= start) {
          callback(new Error("结束时间必须晚于开始时间"))
        } else {
          callback()
        }
      } else {
        callback()
      }
    },
    getCardBackgroundColor() {
      const percentage = this.overtimePercentage;
      if (percentage < 60) {
        return '#E5F6FF'; // 浅蓝，加班时长较少
      } else if (percentage < 80) {
        return '#FFF6CC'; // 浅黄，加班时长中等
      } else {
        return '#FFEBEB'; // 浅红，加班时长较多
      }
    }
  }
};
</script>

<style scoped>

.box-card {
  cursor: pointer;
  transition: all 0.3s;
  border-radius: 16px; /* 增加圆角 */
  background-color: #8B3E2F; /* 修改为较暗的背景颜色 */
}
.box-card:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.2);
  transform: scale(1.02); /* 悬停时缩放效果 */
}
.statistic-card {
  text-align: center;
  padding: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.statistic-icon {
  font-size: 48px; /* 增大图标尺寸 */
  color: #ff8c00; /* 更鲜明的图标颜色 */
  margin-bottom: 10px;
}
.statistic-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 5px;
}
.statistic-value {
  font-size: 24px;
  color: #303133;
  font-weight: bold;
}
.overtime-tips {
  margin-top: 10px;
  padding: 10px;
  background-color: #fff0b3; /* 修改为较暗的背景颜色 */
  border-radius: 4px;
  color: #ff8c00; /* 更鲜明的文字颜色 */
  display: flex;
  align-items: center;
}
.overtime-tips i {
  margin-right: 5px;
}
.health-tips {
  margin-top: 10px;
  color: #F56C6C;
  font-size: 14px;
}
.mt-10 {
  margin-top: 10px;
}

/* 现代化按钮样式 */
.modern-button {
  border-radius: 4px;
  transition: all 0.3s;
}
.modern-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 现代化卡片样式 */
.modern-card {
  border-radius: 8px;
  background-color: #e9e9e9; /* 修改为较暗的背景颜色 */
}

/* 现代化表格样式 */
.modern-table {
  border-radius: 8px;
  overflow: hidden;
}
.modern-table th {
  background-color: #e5e7eb; /* 修改为较暗的背景颜色 */
}

/* 现代化状态按钮样式 */
.modern-status-btn {
  border-radius: 4px;
}

/* 现代化操作按钮样式 */
.modern-action-btn {
  color: #409EFF;
  transition: all 0.3s;
}
.modern-action-btn:hover {
  color: #2d79b6;
}

/* 现代化对话框样式 */
.modern-dialog {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 动画进度条样式 */
.animated-progress .el-progress-bar__inner {
  transition: width 1s ease-in-out; /* 进度条动画效果 */
}
</style>
